package com.whub507.msgmanager.task;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class DynamicScheduledTaskRegistrar extends ScheduledTaskRegistrar {

    private final Map<String, ScheduledTask> scheduledTaskMap = new ConcurrentHashMap<>();

    @Autowired
    TaskScheduler taskScheduler;

    /**
     * 新增任务
     * @param taskName
     * @param cron
     * @param runnable
     */
    public Boolean addCronTask(String taskName,String cron,Runnable runnable){
        if(scheduledTaskMap.containsKey(taskName)){
            return Boolean.FALSE;
        }
        CronTask cronTask = new CronTask(runnable,cron);
        ScheduledTask scheduledTask = this.scheduleCronTask(cronTask);
        scheduledTaskMap.put(taskName,scheduledTask);
        return Boolean.TRUE;
    }

    /**
     * 修改动态任务
     * @param taskName
     * @param cron
     */
    public void updateTask(String taskName,String cron,Runnable runnable) {
        cancelCronTask(taskName);
        addCronTask(taskName, cron,runnable);
    }

    /**
     * 删除任务
     * @param taskName
     */
    public void cancelCronTask(String taskName){
        ScheduledTask scheduledTask = scheduledTaskMap.get(taskName);
        if(null != scheduledTask){
            scheduledTask.cancel();
            scheduledTaskMap.remove(taskName);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        scheduledTaskMap.values().forEach(ScheduledTask::cancel);
    }
}
